import Storage from "../../utils/storage"
import Console from '../../utils/console.js'
// 安全重试执行器
const executeRetryQueue = (queue) => {
	queue.reduce((chain, [key, request], index) => {
		return chain.then(() => {
			return new Promise(resolve => {
				// 添加递增延迟：0ms, 20ms, 40ms...
				setTimeout(() => {
					request.retry().finally(() => {
						resolve()
					})
				}, index * 20)
			})
		})
	}, Promise.resolve())
}

const auth = {
	state: {
		token: Storage.getSync('token') || null,
		loginIng: false,
		requestsQueue: new Map() // 请求重试队列
	},
	mutations: {
		// 正在尝试登录中
		SET_LOGINING(state, status) {
			state.loginIng = status;
		},
		// 添加列队
		ADD_QUEUE(state, request) {
			const requestKey = request.config.header['RequestID'];
			state.requestsQueue.set(requestKey, request)
		},
		// 删除队列中的某一个
		DEL_QUEUE_BY_KEY(state, key) {
			state.requestsQueue.delete(key)
		},
		// 遍历队列执行
		FOREACH_QUEUE(state) {
			state.loginIng = false;
			executeRetryQueue(Array.from(state.requestsQueue))
		},
		// 重新设置token
		SET_TOKEN(state, value) {
			state.token = value;
			Storage.setSync('token', value)
		},
		// 跳转登录页
		TO_LOGIN() {
			uni.navigateTo({
				url: '/pages/login/login'
			})
		},
		LOGIN_OUT(state) {
			state.token = null;
			Storage.removeSync('token')
		}
	},
	actions: {
		logOutReset({
			commit
		}) {
			commit('LOGIN_OUT');
			commit('RESET_USERINFO', null, {
				root: true
			})
		}

	}
}

export default auth